<?php
    /**
     * Created by PhpStorm.
     * User: mybook-lhp
     * Date: 18/8/9
     * Time: 下午3:27
     */

    namespace app\face2market\logic;

    use app\common\utils\UtilRedisBase;
    use app\member\model\MemberModel;

    class SendMessageRedis
    {

        /**
         * 发送信息到redis
         * @param $phones
         * @return string
         */
        public function SendMessage($phones = [], $content = '')
        {
            if (empty($phones)) {
                return 'no ';
            }
            foreach ($phones as $key => $item) {
                $members[$key]['number'] = 0;
                $members[$key]['phone'] = $item['phone'];
            }

            $lot = 1;

            $Redis = UtilRedisBase::getInstance(config('redis'));
            $message['lot'] = $lot;
            $message['content'] = $content;
            $Redis->rPush('message_all', json_encode($message));
            foreach ($members as $member) {
                $Redis->rPush('phone_' . $message['lot'], json_encode($member));

            }
        }

        /**
         * 后端运行
         */
        public function run()
        {

            $Redis = UtilRedisBase::getInstance(config('redis'));

            $message = json_decode($Redis->lPop('message_all'), true);

            if ($message) {
                $this->runSend($Redis, $message);
            }
        }

        /**
         * 反复执行直到完成
         *
         * @param     $Redis
         * @param     $message
         * @param int $lLen
         */
        protected function runSend($Redis, $message, $lLen = 0)
        {
            $phone = json_decode($Redis->lPop('phone_' . $message['lot']), true);
            if ($phone && $phone['number'] < 3) {
                $lLen = $Redis->lLen('phone_' . $message['lot']) + $lLen;
                $o_lLen = 0;
                for ($i = 1; $i <= $lLen; $i++) {
                    if (!$this->send($phone['phone'], $message['content'])) {
                        $phone['number']++;
                        $Redis->rPush('phone', json_encode($phone));
                        $o_lLen++;
                    }
                }
                $this->runSend($Redis, $message, $o_lLen);
            }
        }

        /**
         * 发送短信
         *
         * @param $data
         * @param $content
         *
         * @return mixed
         */
        protected function send($phone, $content)
        {
            return plugin_action('TencentSms', 'TencentSms', 'sendMessage', [
                'phoneNum' => $phone,
                'content' => $content
            ]);
        }

        public function send_one($Redis, $phone, $content, $o_lLen = 0)
        {
            if (!$this->send($phone, $content) && $o_lLen > 3) {

                $this->send($phone, $content);

            } else {
                $Redis->rPush('phone', json_encode($phone));
            }
            $o_lLen++;
        }


    }